//
//  AppDelegate.swift
//  BEGlobalOiler
//
//  Created by KKING on 16/7/25.
//  Copyright © 2016年 Bullseye Energy pte ltd. All rights reserved.
//  AIzaSyBP9SuuolZsKo-Qi_EloEe7-wR-zdlluEg
//  sfci50a7csc8i

import UIKit
import IQKeyboardManagerSwift
import GoogleMaps

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    var hostReach: Reachability?
    var networkState = 0
    
    var locationManager = CLLocationManager()
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
        
        //打印沙盒地址
        //print(BEAccountModel.accountPath)
        setupNotificationSettings()
        setupRootViewController() // 配置控制器
        setupGlobalStyle()        // 配置全局样式
        setupGlobalData()         // 配置全局数据
        setupOthers()             // 配置其他内容(地图,定位,键盘)
        setupReachability()       // 配置网络检测
        setupIM()                 // IM相关配置
        return true
    }
    
    /**
     设置根控制器,增加新特性
     */
    private func setupRootViewController(){
        
        //获取当前版本号
        let newVersion = getCurrentVersion()

//        正式版
//        var oldVersion: String = "\(0.0)"
//        <
        
        var oldVersion: String = "\(1.0)"
        //获取旧版本号
        if UserDefaults.standard.object(forKey: "version") != nil{
            oldVersion = UserDefaults.standard.object(forKey: "version") as! String
        }
        
        window = UIWindow(frame: SCREEN_BOUNDS)
        //比较两者
        if oldVersion == newVersion {
            //存储新版本到沙盒中
            UserDefaults.standard.set(newVersion, forKey: "version")
            UserDefaults.standard.synchronize()
            window?.rootViewController = BENewController()
        }else{
            window?.rootViewController = BEMainTabBarController()
        }
        Thread.sleep(forTimeInterval: 2.0)
        window?.makeKeyAndVisible()

//        let whiteView = UIView(frame: CGRect.zero)
//        whiteView.size = CGSize(width: SCREEN_WIDTH, height: 300)
//        whiteView.center = (self.window?.center)!
//        whiteView.backgroundColor = UIColor.white
//        whiteView.alpha = 0
//        self.window?.addSubview(whiteView)
//        UIView.animate(withDuration: 3.0, animations: {
//            whiteView.alpha = 1
//        }) { (_) in
//            whiteView.removeFromSuperview()
//        }
    }
    
    private func setupIM(){
        RCIM.shared().initWithAppKey("sfci50a7csc8i")
    }
    
    
    
    /**
     配置网络检测
     */
    private func setupReachability() {
        NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(notification:)), name: NSNotification.Name.reachabilityChanged, object: nil)
        hostReach = Reachability.forInternetConnection()
        hostReach?.startNotifier()
    }
    
    //远程推送
    private func setupNotificationSettings(){
        let notificatonSettings = UIUserNotificationSettings(types: [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound], categories: nil)
        UIApplication.shared.registerUserNotificationSettings(notificatonSettings)
        UIApplication.shared.registerForRemoteNotifications()
        
    }
    
    /**
     传递deviceToken注册远程通知
     */
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        //此处需要把deviceToken保存起来,然后在登录的时候发送给服务器
        let userDefault = UserDefaults.standard
        userDefault.set("\(deviceToken)", forKey: "deviceToken")
        userDefault.synchronize()
    }
    
    /**
     注册远程通知失败
     */
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("did Fail To Register For Remote Notifications With Error: \(error)")
    }
    
    //接收到远程推送通知时调用
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        completionHandler(UIBackgroundFetchResult.newData)
        
        if application.applicationState == .background || application.applicationState == .inactive {
            //此处增加跳转逻辑
        } else if application.applicationState == .active {
            guard let message = userInfo as? [String: [String: AnyObject]] else {
                return
            }
            let alertC = UIAlertController(title: "收到新的消息", message: message["aps"]?["alert"] as! String?, preferredStyle: UIAlertControllerStyle.alert)
            let confrimAction = UIAlertAction(title: "查看", style: UIAlertActionStyle.destructive, handler: { (action) in
                //此处增加跳转逻辑
            })
            let cancelAction = UIAlertAction(title: "忽略", style: UIAlertActionStyle.default, handler: { (action) in
                //什么也不做
            })
            alertC.addAction(confrimAction)
            alertC.addAction(cancelAction)
            UIApplication.shared.keyWindow?.rootViewController?.present(alertC, animated: true, completion: nil)
        }
        
    }
    /**
     监听网络状态改变
     */
    @objc func reachabilityChanged(notification: NSNotification) {
        
        guard let curReach = notification.object as? Reachability else {
            return
        }
        
        switch curReach.currentReachabilityStatus() {
        case NotReachable:
            print("无网络")
        case ReachableViaWiFi:
            networkState = 1
            print("WiFi")
        case kReachableVia2G:
            networkState = 2
            print("2G")
        case kReachableVia3G:
            networkState = 3
            print("3G")
        case kReachableVia4G:
            networkState = 4
            print("4G")
        default:
            print("未知")
        }
    }
    
    /**
     配置全局数据
     */
    private func setupGlobalData() {
        // 验证缓存的账号是否有效
        BEAccountModel.checkToken()
    }
    
    
    /**
     全局样式
     */
    private func setupGlobalStyle() {
        UIApplication.shared.isStatusBarHidden = true
        //        UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default
        JFProgressHUD.setupHUD() // 配置HUD
    }
    
    
    /**
     其他设置
     */
    private func setupOthers() {
        //        谷歌地图API
        GMSServices.provideAPIKey("AIzaSyBP9SuuolZsKo-Qi_EloEe7-wR-zdlluEg")
        
        //swift字符串转OC 然后和OCdouble进行比较大小
        if UIDevice.current.systemVersion._bridgeToObjectiveC().doubleValue >= 8.0{
            locationManager.requestWhenInUseAuthorization()
        }
        //键盘IQKeyboard 基本设置
        IQKeyboardManager.sharedManager().enable = true
        IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true
        
        //获得平台信息 并沙盒存储
        //        JFProgressHUD.showWithStatus(status: "Loading")
        getPlatformInfo()
    }
    
    private func getPlatformInfo(){
        //此处静默加载一些数据并沙盒缓存
        showNetworkActivity()
        BENetworkTools.shareNetworkTool.getPlatformInfo { (success, result, error) in
            guard let resultjson = result else {
                //                JFProgressHUD.showWithStatus(status: "Network fault!")
                return
            }
            if resultjson["success"] == true {
                
                let phone = resultjson["result"]["phone"].stringValue
                let accountNo = resultjson["result"]["accountNo"].stringValue
                //沙盒保存
                UserDefaults.standard.set(phone, forKey: "phone")
                UserDefaults.standard.set(accountNo, forKey: "accountNo")
                UserDefaults.standard.synchronize()
                
                //                JFProgressHUD.showSuccessWithStatus(status: "Data loading successfully!")
            } else {
                //                JFProgressHUD.showInfoWithStatus(status: resultjson["message"].stringValue)
            }
        }
    }
    
}

extension AppDelegate {
    ///获取当前版本号
    func getCurrentVersion() -> String {
        //获取当前版本
        let infoDict = Bundle.main.infoDictionary
        let version = infoDict!["CFBundleShortVersionString"] as! String
        return version
    }
    
    //    //版本号所在的沙盒路径
    //    let versionPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!.stringByAppendingString("/VersionPlist.plist")
}
